function [ is_converged, states ] = CheckConvergence( x,states  )
% check if the result has converged

%-------------------------TUNNING FACTORS----------------------------------
% critical  value 
Dif_Fr_C = 100;   % crtical fr difference (squared)
Dif_Cdl_C = 0.01;  % crtical cdL difference (squared)
%--------------------------------------------------------------------------

Cd_previous = states(1);
Cr_previous = states(2);
dif_Cd_mean = states(3);
dif_Cr_mean = states(4);

Cd=x(1);
Cr=x(2);

% difference from previous results
dif_Cd= (Cd-Cd_previous).^2;
dif_Cr= (Cr-Cr_previous).^2;

% go through a low pass filter
[ dif_Cd_mean ] = LowPassFilter( dif_Cd_mean,dif_Cd,0.5);
[ dif_Cr_mean ] = LowPassFilter( dif_Cr_mean,dif_Cr,0.5);
             
if ( dif_Cr_mean < Dif_Fr_C) &&( dif_Cd_mean < Dif_Cdl_C)
   is_converged = true;
else 
   is_converged = false;
end
                
states=[x(1), x(2), dif_Cd_mean, dif_Cr_mean];    
end

